<template>
  <div class="fullMain">
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert">{{ alertText }}</alert>
    </div>
    <!-- 提醒时间选择 -->
    <alarmTime
      :isShowAlarmTime.sync="isShowAlarmTime"
      :remindInfo="remindInfo"
      @getPickedReplayTime="getPickedReplayTime"
    ></alarmTime>
    <!--顶部标题 -->
    <div style="position: fixed; width: 100%">
      <x-header
        class="header"
        :left-options="{ backText: '阶段目标', showBack: true }"
      >
        <a slot="right" @click="deleteGoal">删除</a>
      </x-header>
    </div>
    <div style="height: 20px; background-color: rgb(237, 237, 237)" />
    <group class="taskWrap">
      <x-textarea
        title="阶段目标简介："
        v-model="goalContent"
        @on-blur="onBlur"
        placeholder="会自动保存"
      ></x-textarea>
      <div class="timeInfo">
        <div class="picker" @click="isShowDeadline = !isShowDeadline">
          <div>
            <i class="fa fa-clock-o"></i>
            <span>{{
              deadline === "" || deadline === undefined ? "截止日期" : deadline
            }}</span>
          </div>
        </div>
        <div class="picker" @click="isShowAlarmTime = true">
          <div>
            <i class="fa fa-bell-o"></i>
            <span>{{ getAlarmTime() }}</span>
          </div>
        </div>
      </div>
      <span class="alertInfoOfGoal">{{ alertInfoOfGoal }}</span>
      <inline-calendar
        v-if="isShowDeadline"
        ref="calendar"
        class="inline-calendar-demo"
        v-model="deadline"
        @on-select-single-date="onSelect"
        :return-six-rows="false"
        disable-past
        :highlight-weekend="true"
      >
      </inline-calendar>
      <divider>{{ alertInfoOfJob }}</divider>
    </group>
    <editInfo
      class="editInfo-wrap"
      :reportItems.sync="placements"
      addPlaceHolder="添加分工"
    >
      <template slot="chooseItem" slot-scope="scope">
        <div class="picker" @click="addMember(scope.data)">
          <div
            v-if="
              placements[scope.data].userList == undefined ||
              placements[scope.data].userList.length == 0
            "
          >
            <i class="fa fa-user-splus"></i>
            <span>负责人</span>
          </div>
          <div
            v-else
            class="choosedUser"
            v-for="item in placements[scope.data].userList"
            :key="item"
          >
          <span v-if="item.detail !== undefined">{{ item.detail.name }}</span>
            <span
              v-else
              v-for="key in item"
              :key="key"
              >{{ key }}</span
            >&nbsp;
            <!-- 这里的接口改了，没有头像了 -->
            <!-- <img v-if="item.detail!==undefined" :src="item.detail.avatar" /> -->
          </div>
        </div>
      </template>
      <template slot="note" slot-scope="scope">
        {{ placements[scope.data].alertTextOfJob }}
      </template>
    </editInfo>
  </div>
</template>

<script>
import { XHeader, Group, XTextarea, Divider, InlineCalendar } from "vux";
import task from "api/task";
import time from "utilMethods/time.js";
import alarmTime from "components/AlarmTime/alarmTime";
import editInfo from "components/EditInfo/editInfo";
export default {
  components: {
    editInfo,
    XHeader,
    Group,
    XTextarea,
    Divider,
    InlineCalendar,
    alarmTime,
  },
  data() {
    return {
      alertText: "",
      isShowAlert: false,
      goalContent:
        localStorage.getItem("goalContent") != "null"
          ? localStorage.getItem("goalContent")
          : "",
      jobContent: localStorage.getItem("jobContent"),
      memberList: [], //成员列表，传给人员展示页面
      taskItem: "",
      goalMemberChoosedItem: [], //上一次选择的分工负责人
      placements: [], //任务的分工
      goal: {},
      isModifyOld: false, //true是修改，false是新增
      goalId:
        localStorage.getItem("goalId") == null
          ? ""
          : localStorage.getItem("goalId"),
      isShowDeadline: false,
      deadline: "",
      isShowAlarmTime: false,
      remindInfo: {
        remindTime: "",
        remindDays: [],
      },
      alertInfoOfGoal: "",
      isOnBlur: false, //判断是不是只需修改阶段目标简介
      indexOfClick: localStorage.getItem("indexOfClick")
        ? +localStorage.getItem("indexOfClick")
        : -1,
      alertInfoOfJob: "任务分工",
      notSaveIndex: [], //未保存的index
      isFirstToPage: true,
      goal: {},
      flagOfAddMember: false,
    };
  },
  watch: {
    placements: {
      handler() {
        if (this.isFirstToPage) {
          this.isFirstToPage = false;
        } else {
          this.addGoal();
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.getInitItem();
    this.getGoalMemberChoosedItem();
  },
  methods: {
    async deleteGoal() {
      const result = await task.getDeleteGoal(this.goal.goalId);
      if (result.code == 1) {
        this.showAlert("删除成功！");
        this.$router.go(-1);
      } else {
        this.showAlert("删除失败！");
      }
    },
    getInitItem() {
      // 该目标的所有信息
      let temp = localStorage.getItem("goal");
      if (temp.indexOf("placements") === -1) {
        this.flagOfAddMember = true;
      }
      if (temp !== undefined) {
        this.goal = JSON.parse(temp);
        this.isModifyOld = true;
        if (!this.flagOfAddMember) {
          this.deadline = this.goal.deadline;
          this.goal.weeks = this.goal.weeks.filter((item) => {
            return item !== null;
          });
          this.remindInfo = {
            remindTime: this.goal.time,
            remindDays: this.goal.weeks,
          };
        } else {
          //选人过后来的就取缓存的
          this.deadline = localStorage.getItem("deadline");
          this.remindInfo = JSON.parse(localStorage.getItem("remindInfo"));
        }
      }
      // 选中的task
      this.taskItem = localStorage.getItem("taskItem");
      if (!!this.taskItem) {
        this.taskItem = JSON.parse(this.taskItem);
      }
      // if (this.goalId === "" || this.goalId === undefined) {
      //   localStorage.setItem("placements", "");
      // }
      // 该页面的goals,如果goal有值，就用goal的。否则用缓存的
      //如果是选人会来，goal没有更新，这个页面之前删除和新增操作也都没有及时更新
      //因此，再用一个goal的值”member“表示从选人页面来的，取缓存的数据，而不是上一个页面来的数据
      if (this.isModifyOld && !this.flagOfAddMember) {
        this.goalContent = this.goal.goalContent;
        this.placements = this.goal.placements;
      } else {
        let placementsTemp = localStorage.getItem("placements");
        if (
          placementsTemp !== undefined &&
          placementsTemp !== null &&
          placementsTemp !== ""
        ) {
          this.placements = JSON.parse(placementsTemp);
        }
      }
      for(let i=0;i<this.placements.length;++i){
        this.placements[i].index = i;
      }
    },
    getGoalMemberChoosedItem() {
      this.goalMemberChoosedItem = localStorage.getItem(
        "goalMemberChoosedItem"
      );
      if (!!this.goalMemberChoosedItem) {
        this.goalMemberChoosedItem = JSON.parse(this.goalMemberChoosedItem);
      } else {
        this.goalMemberChoosedItem = [];
      }
      if (this.flagOfAddMember) {
        this.placements[
          this.indexOfClick
        ].userList = this.goalMemberChoosedItem;
      }
      localStorage.setItem("goalMemberChoosedItem", []);
    },
    getAlarmTime() {
      if (!this.remindInfo.remindTime) {
        return "不提醒";
      } else {
        let arr = time.weekToChineses(this.remindInfo.remindDays);
        if (arr === "") {
          return "不提醒";
        } else {
          return this.remindInfo.remindTime.substring(0, 5) + " " + arr;
        }
      }
    },
    getPickedReplayTime(val) {
      this.remindInfo = val[0];
      this.isShowAlarmTime = val[1];
      this.isRemind = val[2];
      this.onBlur();
    },
    onSelect(currentValue) {
      this.deadline = currentValue;
      this.isShowDeadline = false;
      this.onBlur();
    },
    onBlur() {
      this.isOnBlur = true;
      this.addGoal();
    },
    addMember(index) {
      this.getMemberList();
      // 这里是为了区分是否从人员选择页面过来，是的话，给goal赋值goalId，判断其直接用页面的缓存
      localStorage.setItem(
        "goal",
        JSON.stringify({ goalId: this.goal.goalId })
      );
      localStorage.setItem("deadline", this.deadline);
      localStorage.setItem("remindInfo", JSON.stringify(this.remindInfo));
      localStorage.setItem("goalContent", this.goalContent);
      localStorage.setItem("indexOfClick", index);
      localStorage.setItem("placements", JSON.stringify(this.placements));
      localStorage.setItem(
        "memberChoosedItem",
        JSON.stringify(this.placements[index].userList)
      );
      this.$router.push({
        name: "ChooseMember",
        params: {
          memberList: this.memberList,
          leaderOrMember: "goalMember",
        },
      });
    },
    getMemberList() {
      if (this.taskItem !== undefined) {
        let executors = this.taskItem.executors;
        let principal = this.taskItem.principal;
        if (executors.length !== 0) {
          executors.forEach((element) => {
            this.memberList.push(element.userId);
          });
        }
        if (principal.length !== 0) {
          principal.forEach((element) => {
            this.memberList.push(element.userId);
          });
        }
      } else {
        this.memberList = [];
      }
    },
    async addGoal() {
      if (!this.judgeData()) {
        return;
      }
      let goalData = this.getGoalData();
      if (this.goalId === "" || this.goalId === undefined) {
        const result = await task.postAddGoal(goalData);
        if (result.code === 1) {
          this.alertInfoOfGoal = this.isOnBlur ? "已自动保存成功" : "";
          this.goalId = result.data;
          this.getAlertInfoOfJob();
          // 这个是解决，第一次创建阶段目标成功后，紧接着创建分工
          localStorage.setItem("goalId", this.goalId);
        } else if (result.code === 0) {
          if (this.isOnBlur) {
            this.alertInfoOfGoal = "自动保存失败，请稍后重试";
          }
          this.showAlert("自动保存失败，请稍后重试");
        }
      } else {
        // 修改postModifyGoal
        const result = await task.postModifyGoal(goalData);
        if (result.code === 1) {
          this.alertInfoOfGoal = this.isOnBlur ? "已自动保存成功" : "";
          this.getAlertInfoOfJob();
        } else if (result.code === 0) {
          if (this.isOnBlur) {
            this.alertInfoOfGoal = "自动保存失败，请稍后重试";
          }
          this.showAlert("【目标分工】修改失败，请重试！");
        }
      }
      localStorage.setItem("placements", JSON.stringify(this.placements));
    },
    getAlertInfoOfJob() {
      if (this.notSaveIndex.length === 0) {
        this.alertInfoOfJob = "任务分工（已保存）";
      } else {
        this.alertInfoOfJob = "请修改第" + this.notSaveIndex + "条分工";
      }
    },
    getGoalData() {
      // if(this.placements===undefined || this.placements.length===0){
      //   return null
      // }
      this.notSaveIndex = [];
      let placementsTemp = [];
      this.placements.forEach((element, index) => {
        if (element.jobContent === null || element.jobContent === "") {
          element.alertTextOfJob = "请填写【内容】";
          this.notSaveIndex.push(index + 1);
        } else if (
          element.userList === undefined ||
          element.userList.length === 0
        ) {
          element.alertTextOfJob = "请选择【负责人】";
          this.notSaveIndex.push(index + 1);
        } else {
          element.alertTextOfJob = "已自动保存";
          placementsTemp.push(this.tempToNeed(element));
        }
      });
      if (this.isModifyOld) {
        this.goalId = this.goal.goalId;
      }
      let temp = {
        deadline: this.deadline,
        time: this.remindInfo.remindTime,
        weeks: time.weekToEnglish(this.remindInfo.remindDays),
        detail: {
          goalContent: this.goalContent.trim(),
          isFinish: false,
          placements: placementsTemp,
        },
        projectId: this.taskItem.projectId,
        goalId: this.goalId,
      };
      return temp;
    },
    judgeData() {
      // 修改阶段目标
      if (this.goalContent.trim() === "") {
        this.alertInfoOfGoal = "请填写【阶段目标简介】";
        return false;
      } else if (!this.deadline) {
        this.alertInfoOfGoal = "请选择【截止日期】";
        return false;
      } else if (
        !this.remindInfo.remindTime ||
        this.remindInfo.remindDays.length === 0
      ) {
        this.alertInfoOfGoal = "请选择【提醒时间】";
        return false;
      } else {
        return true;
      }
    },
    // 将当前页面显示的转为接口需要的
    tempToNeed(temp) {
      if (temp === null) {
        return null;
      }
      let userListTemp = [];
      if (!!temp.userList) {
        temp.userList.forEach((element) => {
          if (element.userId === undefined) {
            userListTemp.push(Object.keys(element)[0]);
          } else {
            userListTemp.push(element.userId);
          }
        });
      }
      return {
        jobContent: temp.jobContent,
        userList: userListTemp,
      };
    },
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
  },
};
</script>

<style lang='less'>
.picker {
  display: inline-block;
  background-color: #dce0e2;
  border-radius: 20px;
  margin: 5px;
  padding: 3px 5px;
  margin-left: 15px;
  span {
    font-size: 12px;
  }
}
.fullMain {
  width: 100%;
  background-color: white;
  .taskWrap {
    .timeInfo {
      .picker;
    }
    .alertInfoOfGoal {
      color: gray;
    }
  }
  .editInfo-wrap {
    .picker {
      .picker;
      display: flex;
      .choosedUser {
        img {
          width: 20px;
          height: 20px;
          vertical-align: middle;
          border-radius: 20px;
        }
      }
    }
  }
}
</style>